package com.yjc.hire.intercept;

import com.yjc.hire.base.BaseInfoProperties;
import com.yjc.hire.exceptions.GraceException;
import com.yjc.hire.grace.result.ResponseStatusEnum;
import com.yjc.hire.utils.IPUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * <p>
 *
 * @author jcyin
 * @since 2025/7/3
 * </p>
 */
@Slf4j
public class SMSIntercept extends BaseInfoProperties implements HandlerInterceptor {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String requestIp = IPUtil.getRequestIp(request);
        Boolean ipExist = redisTemplate.hasKey(MOBILE_SMSCODE + ":" + requestIp);
        log.info("拦截器生效了");
        if (ipExist) {
            log.info("短信发送频率太高了");
            GraceException.disPlay(ResponseStatusEnum.SMS_NEED_WAIT_ERROR);
            return false;
        }

        return true;

    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
